#include <iostream>
#include <stdlib.h>

#include <unistd.h>

using namespace std;

bool GetQueryString(string &query_string)
{
    bool result = false;
    //fd 0&1 已经重定向了
    // cerr << "_______________________________________" << endl;
    // cerr << "Debug CGITest METHOD: " << getenv("METHOD") << endl;
    string method = getenv("METHOD");
    if("GET" == method)
    {
        query_string = getenv("QUERY_STRING");
        // cerr << "Debug GET QUERY_STRING: " << query_string << endl;
        result = true;
    }
    else if("POST" == method)
    {
        // cerr << "Debug Content-Length: " << getenv("CONTENT_LENGTH") << endl;
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char c = 0;
        while(content_length--)
        {
            read(0, &c, 1);
            query_string.push_back(c);
        }
        // cerr << "Debug POST QUERY_STRING: " << query_string << endl;
        result = true;
    }
    else 
    {
        result = false;
    }
    return result;
}

void CutString(string &in, const string &sep, string &out1, string &out2)
{
    auto pos = in.find(sep);
    if(pos != string::npos)
    {
        out1 = in.substr(0, pos);
        out2 = in.substr(pos + sep.size()); 
    }
}

int main()
{
    string query_string;
    if(GetQueryString(query_string))    //a=100&b=200
    {
        string str1, str2;  
        CutString(query_string, "&", str1, str2);  
        string name1, value1, name2, value2;
        CutString(str1, "=", name1, value1);
        CutString(str2, "=", name2, value2);
        //fd = 1
        cout << name1 << ":" << value1 << endl;
        cout << name2 << ":" << value2 << endl;
        //fd = 2
        cerr << name1 << ":" << value1 << endl;
        cerr << name2 << ":" << value2 << endl;
    }
    cerr << "Debug CGIProcess END" << endl;
    return 0;
}